package com.xueyi.core.utils;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 俞烨
 * @version 1.0
 * @description: 日志工具类
 * @date 2023/12/5 14:55
 */
@Slf4j
@Component
public class LogUtil {


    public static final ThreadPoolExecutor LOG_POOL =
            new ThreadPoolExecutor(2, 2, 1, TimeUnit.DAYS,
                    new ArrayBlockingQueue<>(2000),
                    new ThreadPoolExecutor.DiscardPolicy());

    /**
     * 打印info日志，使用方式和Slf4j一样
     *
     * @param format
     * @param arguments
     */
    public void info(String format, Object... arguments) {

        LOG_POOL.execute(() -> {
            try {

                log.info(format, formatArguments(arguments));
            } catch (Exception e) {
                error("发送Info日志出现错误: {}", e.getMessage());
            }
        });
    }

    /**
     * 打印warn日志，使用方式和Slf4j一样
     *
     * @param format
     * @param arguments
     */
    public void warn(String format, Object... arguments) {

        LOG_POOL.execute(() -> {
            log.warn(format, formatArguments(arguments));
        });
    }

    /**
     * 打印error日志，使用方式和Slf4j一样
     *
     * @param format
     * @param arguments
     */
    public void error(String format, Object... arguments) {

        LOG_POOL.execute(() -> {
            log.error(format, formatArguments(arguments));
        });
    }

    private Object[] formatArguments(Object... arguments) {
        Object[] argumentsReal = arguments == null ? null : new Object[arguments.length];

        if (arguments != null) {
            for (int i = 0; i < arguments.length; i++) {
                if (!(arguments[i] instanceof String)) {
                    argumentsReal[i] = JSON.toJSONString(arguments[i]);
                } else {
                    argumentsReal[i] = arguments[i];
                }
            }
        }
        return argumentsReal;
    }
}
